package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.ResponseResultVO;
import com.dc.entity.WorkOrder;
import com.dc.entity.WorkOrderFile;
import com.dc.entity.ro.HiddenDangerOrderRO;
import com.dc.entity.vo.HiddenDangerVO;
import com.dc.enums.OrderType;
import com.dc.enums.OrderTypeEng;
import com.dc.mapper.WorkOrderFileMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.service.HiddenDangerOrderService;
import com.dc.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class HiddenDangerOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements HiddenDangerOrderService {

    @Resource
    private WorkOrderMapper workOrderMapper;
    @Resource
    private WorkOrderFileMapper workOrderFileMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    @Transactional
    public ResponseResultVO insertHiddenDangerOrder(HiddenDangerOrderRO ro) {
        WorkOrder fireWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, fireWorkOrder);
        fireWorkOrder.setId(SnowflakeIdWorker.generateId());
        fireWorkOrder.setReportUserId(Long.valueOf(UserUtil.getUserId()));
        fireWorkOrder.setReportUserName(String.valueOf(redisUtil.get(UserUtil.getUserId())));
        fireWorkOrder.setType(OrderType.HIDDEN.getId());
        fireWorkOrder.setReportUserId(Long.valueOf(UserUtil.getUserId()));
        fireWorkOrder.setReportUserName(String.valueOf(redisUtil.get(UserUtil.getUserId())));
        fireWorkOrder.setNumber(redisUtil.serialNumber("AQYH"));
        if (CollectionUtils.isNotEmpty(ro.getFileIds())) {
            for (String path : ro.getFileIds()) {
                WorkOrderFile WorkOrderFile = new WorkOrderFile();
                WorkOrderFile.setId(SnowflakeIdWorker.generateId());
                WorkOrderFile.setWorkOrderId(fireWorkOrder.getId());
                WorkOrderFile.setFilePath(path);
                workOrderFileMapper.insert(WorkOrderFile);
            }
        }
        int i = workOrderMapper.insert(fireWorkOrder);
        if (i > 0) {
            if (!CommonCodeUtil.increasing(OrderTypeEng.HIDDEN.getName())) {
                //如果缓存为空，则查数据库再插入到redis
                Integer integer = workOrderMapper.selectCount(new QueryWrapper<WorkOrder>().lambda().eq(WorkOrder::getType, OrderType.HIDDEN.getId()));
                redisUtil.set(OrderTypeEng.HIDDEN.getName(), 0 == integer ? 1 : integer);
            }
        }
        return ResponseResultVO.insertResult(i);
    }

    @Override
    @Transactional
    public ResponseResultVO updateHiddenDangerOrder(HiddenDangerOrderRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WorkOrder hiddenDangerOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, hiddenDangerOrder);
        workOrderFileMapper.delete(new QueryWrapper<WorkOrderFile>().lambda().eq(WorkOrderFile::getWorkOrderId, ro.getId()));
        if (CollectionUtils.isNotEmpty(ro.getFileIds())) {
            for (String path : ro.getFileIds()) {
                WorkOrderFile WorkOrderFile = new WorkOrderFile();
                WorkOrderFile.setId(SnowflakeIdWorker.generateId());
                WorkOrderFile.setWorkOrderId(hiddenDangerOrder.getId());
                WorkOrderFile.setFilePath(path);
                workOrderFileMapper.insert(WorkOrderFile);
            }
        }
        return ResponseResultVO.updateResult(workOrderMapper.updateById(hiddenDangerOrder));
    }

    @Override
    @Transactional
    public ResponseResultVO deleteHiddenDangerOrder(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        workOrderFileMapper.delete(new QueryWrapper<WorkOrderFile>().lambda().in(WorkOrderFile::getWorkOrderId, idList));
        int deleteBatchIds = workOrderMapper.deleteBatchIds(idList);
        if (deleteBatchIds > 0) {
            redisUtil.diminishing(OrderTypeEng.HIDDEN.getName(), deleteBatchIds);
        }
        return ResponseResultVO.deleteResult(deleteBatchIds);
    }

    @Override
    public ResponseResultVO selectHiddenDangerOrderList(HiddenDangerOrderRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        //条件构造
        //是否是H5
        if (StringUtils.isNotBlank(ro.getClient()) && "H5".equalsIgnoreCase(ro.getClient())) {
            queryWrapper.lambda().eq(WorkOrder::getReportUserId, UserUtil.getUserId());
        }
        queryWrapper.lambda().eq(WorkOrder::getType, OrderType.HIDDEN.getId());
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(ro.getIds()), WorkOrder::getId, ro.getIds());
        queryWrapper.orderBy(StringUtils.isNotBlank(ro.getOrderByColumn()), "asc".equalsIgnoreCase(ro.getIsAsc()) ? true : false, StringUtils.toLine(ro.getOrderByColumn()));
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getNumber()), WorkOrder::getNumber, ro.getNumber());
        queryWrapper.lambda().eq(null != ro.getReportUserId(), WorkOrder::getReportUserId, ro.getReportUserId());
        queryWrapper.lambda().eq(null != ro.getStatus(), WorkOrder::getStatus, ro.getStatus());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getGrade()), WorkOrder::getGrade, ro.getGrade());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getFactor()), WorkOrder::getFactor, ro.getFactor());
        queryWrapper.lambda().eq(StringUtils.isNotBlank(ro.getRegionName()), WorkOrder::getRegionName, ro.getRegionName());
        //上报时间区间查询
        queryWrapper.apply(StrUtil.isNotBlank(ro.getCreateTime()),
                "date_format (create_time,'%Y-%m-%d') >= date_format('" + ro.getCreateTime() + "','%Y-%m-%d')");
        queryWrapper.apply(StrUtil.isNotBlank(ro.getEndTime()),
                "date_format (create_time,'%Y-%m-%d') < date_format('" + ro.getEndTime() + "','%Y-%m-%d')");
        queryWrapper.lambda().orderByDesc(WorkOrder::getCreateTime);
        Page<WorkOrder> pageData = workOrderMapper.selectPage(page, queryWrapper);
        List<HiddenDangerVO> fireVOS = ListBeanUtils.listCopyMapper(pageData.getRecords(), WorkOrder.class, HiddenDangerVO.class);
        List<WorkOrderFile> WorkOrderFiles = Collections.EMPTY_LIST;
        if (CollectionUtils.isNotEmpty(fireVOS)) {
            WorkOrderFiles = workOrderFileMapper.selectList(new QueryWrapper<WorkOrderFile>().lambda().in(WorkOrderFile::getWorkOrderId, fireVOS
                    .stream().map(HiddenDangerVO::getId).collect(Collectors.toList())));
            List<WorkOrderFile> finalWorkOrderFiles = WorkOrderFiles;
            fireVOS.forEach(s -> {
                s.setFiles(finalWorkOrderFiles.stream().filter(p -> p.getWorkOrderId().equals(s.getId())).collect(Collectors.toList()));
            });
        }

        return ResponseResultVO.resultPageList(fireVOS, ro);
    }

    @Override
    public void hiddenDangerOrderRecordExport(HttpServletResponse response, HiddenDangerOrderRO ro) {
        ResponseResultVO roadReportForm = this.selectHiddenDangerOrderList(ro);
        HashMap<String, Object> data = (HashMap<String, Object>) roadReportForm.getData();
        ExportUtil.exportExcelNew("安全隐患记录", (List) data.get("list"), HiddenDangerVO.class, response);
    }
}
